package com.example.backspring.Service.impl;

import com.example.backspring.Service.LLMService;
import com.example.backspring.config.Message;
import com.example.backspring.config.deepseekSample;
import com.google.gson.*;
import com.tencentcloudapi.common.CommonClient;
import com.tencentcloudapi.common.CommonRequest;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.SSEResponseModel;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class LLMServiceImpl implements LLMService {
    public static class CustomSSEResponse extends SSEResponseModel {
        public String Response;
        private String RequestId;

        @Override
        public String getRequestId() {
            return RequestId;
        }

        @Override
        public void setRequestId(String requestId) {
            RequestId = requestId;
        }
    }

    public static class CustomSSEResponseDeserializer implements JsonDeserializer<deepseekSample.CustomSSEResponse> {
        @Override
        public deepseekSample.CustomSSEResponse deserialize(JsonElement jsonElement, Type type,
                                                            JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            deepseekSample.CustomSSEResponse resp = new deepseekSample.CustomSSEResponse();
            resp.Response = jsonElement.toString();
            return resp;
        }
    }

    @Override
    public Message queryLLM(String asker, String moxing, String endpoint, String region, double temperature, Integer maxTokens) {
        Message message = new Message();
        message.setStatus(200);
        StringBuilder fullResponse = new StringBuilder();

        try {
// 凭证和客户端初始化（保持原样）
            Credential cred = new Credential("AKIDMo490f7LLHBuSozxhEbmkkW4OUM0c3GF", "pRWUHrENJ3at6EAsPinfKyQeeS2OXVM0");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endpoint);
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CommonClient client = new CommonClient("lkeap", "2024-05-22", cred, region, clientProfile);

// 请求参数构造（保持原样）
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("Model", moxing);
            Map<String, String> messageMap = new HashMap<>();
            messageMap.put("Role", "user");
            messageMap.put("Content", asker);
            paramsMap.put("Messages", List.of(messageMap));
            paramsMap.put("Stream", true);
            paramsMap.put("Temperature", temperature);
            paramsMap.put("MaxTokens", maxTokens != null ? maxTokens : null);

// 发送请求
            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(deepseekSample.CustomSSEResponse.class, new deepseekSample.CustomSSEResponseDeserializer())
                    .create();
            CommonRequest req = new CommonRequest(gson.toJson(paramsMap));
            client.gson = gson;

// 处理流式响应
            deepseekSample.CustomSSEResponse resp = client.commonRequest(req, "ChatCompletions", deepseekSample.CustomSSEResponse.class);
            if (resp.isStream()) {
                for (SSEResponseModel.SSE e : resp) {
                    shuchu(e.Data); // 打印片段内容
                    String chunkContent = parseContentFromChunk(e.Data); // 解析片段内容
                    if (chunkContent != null) {
//                        System.out.print(chunkContent);
//                        log.info(chunkContent);
                        fullResponse.append(chunkContent);
                    }
                }
            } else {
                fullResponse.append(resp.Response);
            }
//            log.info(fullResponse.toString());
            message.setDeepseekData(fullResponse.toString());
            return message;

        } catch (TencentCloudSDKException e) {
            message.setStatus(500);
            message.setMessage("请求失败: " + e.getMessage());
            return message;
        }
    }

    // 新增方法：从流式数据块中提取内容
    private String parseContentFromChunk(String jsonStr) {
        try {
            JsonElement jsonElement = new Gson().fromJson(jsonStr, JsonElement.class);
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObj = jsonElement.getAsJsonObject();
                JsonArray choices = jsonObj.getAsJsonArray("Choices");
                if (choices != null && !choices.isEmpty()) {
                    JsonObject delta = choices.get(0).getAsJsonObject().getAsJsonObject("Delta");
                    if (delta != null && delta.has("Content")) {
                        return delta.get("Content").getAsString();
                    }
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
    public static void shuchu(String jsonStr) {
        Gson gson = new Gson();
        JsonElement jsonElement = gson.fromJson(jsonStr, JsonElement.class);

        if (jsonElement.isJsonObject()) {
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            JsonArray choicesArray = jsonObject.getAsJsonArray("Choices");
            if (choicesArray != null && !choicesArray.isEmpty()) {
                for (JsonElement choiceElement : choicesArray) {
                    if (choiceElement.isJsonObject()) {
                        JsonObject choice = choiceElement.getAsJsonObject();
                        JsonObject delta = choice.getAsJsonObject("Delta");
                        if (delta != null && delta.has("Content")) {
                            String content = delta.get("Content").getAsString();
                            System.out.print(content);
                        }
                    }
                }
            }
        } else if (jsonElement.isJsonArray()) {
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            for (JsonElement element : jsonArray) {
                if (element.isJsonObject()) {
                    JsonObject jsonObject = element.getAsJsonObject();
                    JsonArray choicesArray = jsonObject.getAsJsonArray("Choices");
                    if (choicesArray != null && !choicesArray.isEmpty()) {
                        for (JsonElement choiceElement : choicesArray) {
                            if (choiceElement.isJsonObject()) {
                                JsonObject choice = choiceElement.getAsJsonObject();
                                JsonObject delta = choice.getAsJsonObject("Delta");
                                if (delta != null && delta.has("Content")) {
                                    String content = delta.get("Content").getAsString();
                                    System.out.print(content);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}


